import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wechat_kit/wechat_kit.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/pay/model/order_info_req.dart';
import 'package:tracker/common/pay/wxpay_utils.dart';
import 'package:tracker/pages/login/model/login_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

const int payLoadingCountDownTime = 60;

/// 取消支付跳转的网页
const String payCancelUrl = 'https://xlwwh5.xlwwapp.top/alipay/return?cancel=1';

/// 支付页webview
class PayWebViewPage extends ConsumerStatefulWidget {
  const PayWebViewPage({super.key, required this.url, this.title});

  final String url;
  final String? title;

  @override
  ConsumerState<PayWebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends ConsumerState<PayWebViewPage> with WidgetsBindingObserver {
  final wxpayUtils = WxpayUtils();

  // 是否小程序支付
  bool isMiniAppPay = false;

  String title = '';

  /// 是否是跳转app操作
  bool isLaunchAlipayApp = false;

  /// 已经打开过app，申请拉起app，拉一次只能打开app一次
  bool isLaunchAlipayOpened = false;

  /// app是否从前台切换到后台
  bool isAppInactive = false;

  /// 倒计时时长（秒）
  int countDownTime = payLoadingCountDownTime;

  /// 倒计时（秒）
  int countDown = payLoadingCountDownTime;

  /// 倒计时定时器
  final timerUtil = TimerUtil(mTotalTime: payLoadingCountDownTime * 1000);

  /// 是否显示倒计时
  bool isShowCountDown = false;

  /// 进度条进度
  double progress = 1;

  final GlobalKey webViewKey = GlobalKey();
  InAppWebViewController? webViewController;

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
    crossPlatform: InAppWebViewOptions(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
      minimumFontSize: 17,
      // 是否缓存
      cacheEnabled: false,
      clearCache: true,
    ),
    android: AndroidInAppWebViewOptions(
      useHybridComposition: true,
    ),
    ios: IOSInAppWebViewOptions(
      allowsInlineMediaPlayback: true,
    ),
  );

  /// 注入参数
  _injectParams(Uri uri) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    // 复制一份新的参数
    Map<String, String> queryParameters = Map<String, String>.from(uri.queryParameters);
    // final queryParameters = uri.queryParameters;
    var needReload = false;
    // 是否包含token
    if (!queryParameters.containsKey('token')) {
      LoginData loginData = SpUtil.getObj('loginData', (v) => LoginData().fromJson(v), defValue: LoginData());
      queryParameters['token'] = loginData.token ?? '';
      needReload = true;
    }
    // 是否包含appId
    if (!queryParameters.containsKey('appId')) {
      queryParameters['appId'] = Env.envConfig.wxAppId;
      needReload = true;
    }
    // 是否包含imei
    if (!queryParameters.containsKey('imei')) {
      queryParameters['imei'] = deviceInfo.imei ?? '';
      needReload = true;
    }
    // 是否包含iccid
    if (!queryParameters.containsKey('iccid')) {
      queryParameters['iccid'] = deviceInfo.iccid ?? '';
      needReload = true;
    }
    // 是否包含closePage
    if (queryParameters.containsKey('closePage')) {
      // 关闭当前页面
      context.pop();
      return;
    }
    // 是否包含buildNumber
    if (!queryParameters.containsKey('buildNumber')) {
      queryParameters['buildNumber'] = Env.envConfig.buildNumber;
      needReload = true;
    }
    // platform
    if (!queryParameters.containsKey('platform')) {
      queryParameters['platform'] = Platform.isAndroid ? 'android' : 'ios';
      needReload = true;
    }

    if (needReload) {
      // 重新加载
      final newUrl = uri.replace(queryParameters: queryParameters).toString();
      XLogger.debug('newUrl: $newUrl');
      // 停止加载
      await webViewController?.stopLoading();
      await webViewController?.loadUrl(urlRequest: URLRequest(url: Uri.parse(newUrl)));
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // 倒计时
      timerUtil.setOnTimerTickCallback((int tick) {
        setState(() {
          countDown = tick ~/ 1000;
          XLogger.debug('countDown: $countDown');
          // 进度条进度
          progress = (payLoadingCountDownTime - countDown) / payLoadingCountDownTime;
        });
        // 倒计时结束，跳转到取消支付网页
        if (countDown == 0) {
          _jumpToPayCancel();
          // 取消支付
          timerUtil.cancel();
          // 取消支付后，不能再拉起app
          isLaunchAlipayApp = false;
          setState(() {
            isShowCountDown = false;
          });
        }
      });
    });
    wxpayUtils.registerWechatResp((resp) {
      if (resp is WechatLaunchMiniProgramResp) {
        XLogger.info('拉起小程序: ${resp.errorCode} ${resp.errorMsg}, isSuccessful: ${resp.isSuccessful}');
        XLogger.info('拉起小程序 exMsg: ${resp.extMsg}');
        if (resp.isSuccessful) {
          // 支付成功
          ToastUtils.showSimpleDialog(context,
              title: '提示', content: '购买成功', confirmTitle: '好的', confirmCallback: () {});
        } else {
          // 支付失败
          ToastUtils.showToast('支付失败');
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    timerUtil.cancel();
    WidgetsBinding.instance.removeObserver(this);
    wxpayUtils.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    XLogger.debug('didChangeAppLifecycleState: $state');
    switch (state) {
      case AppLifecycleState.inactive:
        if (!isMiniAppPay) {
          isAppInactive = true;
          // 应用程序处于非活动状态，并且未接收用户输入时调用
          _startShowLoading();
        }
        break;
      case AppLifecycleState.resumed:
        // 应用程序可见，前台
        // XLogger.debug('开始倒计时！！！');
        // if (isAppInactive && isLaunchAlipayApp) {
        //   timerUtil.setTotalTime(countDownTime * 1000);
        //   timerUtil.startCountDown();
        // }
        isAppInactive = false;
        break;
      case AppLifecycleState.paused:
        // 应用程序不可见，后台
        break;
      case AppLifecycleState.detached:
        // 申请将暂时暂停
        break;
      case AppLifecycleState.hidden:
        // 应用程序不可见，后台
        break;
    }
  }

  bool _isPayScheme(String url) {
    return url.startsWith('alipay://') || url.startsWith('alipays://') || url.startsWith('weixin://');
  }

  /// 开始显示支付倒计时
  _startShowLoading() {
    if (isLaunchAlipayApp && !isLaunchAlipayOpened) {
      XLogger.debug('_startShowLoading');
      // 打开支付倒计时网页
      timerUtil.setTotalTime(countDownTime * 1000);
      Future.delayed(const Duration(seconds: 3), () {
        XLogger.debug('打开支付倒计时网页');
        setState(() {
          isShowCountDown = true;
          progress = 1;
        });
        isLaunchAlipayOpened = true;
        timerUtil.startCountDown();
      });
    }
  }

  _jumpToPayCancel() async {
    // 跳转到取消支付网页
    await webViewController?.loadUrl(urlRequest: URLRequest(url: Uri.parse(payCancelUrl)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title, style: const TextStyle(color: Colors.white)),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: Stack(
        children: [
          InAppWebView(
            key: webViewKey,
            initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
            initialOptions: options,
            onWebViewCreated: (controller) {
              webViewController = controller;
              controller.addJavaScriptHandler(
                  handlerName: 'createWebViewMiniAppOrder',
                  callback: (args) {
                    XLogger.debug('createWxOrder: $args');
                    // 将json字符串转为OrderInfoReq
                    final orderInfoReq = OrderInfoReq.fromJson(args[0]);
                    XLogger.debug('orderInfoReq: ${orderInfoReq.toJson()}');
                    isMiniAppPay = true;
                    wxpayUtils.createMiniAppOrder(orderInfoReq);
                  });
            },
            onTitleChanged: (controller, newTitle) {
              setState(() {
                title = newTitle ?? '';
              });
            },
            onUpdateVisitedHistory: (controller, url, androidIsReload) {
              // print('onUpdateVisitedHistory: $url');
              // XLogger.debug('onUpdateVisitedHistory: $url');
            },
            shouldOverrideUrlLoading: (controller, navigationAction) async {
              XLogger.debug('shouldOverrideUrlLoading: ${navigationAction.request.url}');
              var uri = Uri.parse(navigationAction.request.url.toString());
              // 处理微信返回事件
              if (uri.host.contains('wxpaycallback')) {
                // 跳转到支付结果页面
                await webViewController?.stopLoading();
                await controller.loadUrl(
                    urlRequest: URLRequest(url: Uri.parse('https://xlwwh5.xlwwapp.top/return/wechat')));
                return NavigationActionPolicy.CANCEL;
              }
              if (![
                "http",
                "https",
              ].contains(uri.scheme)) {
                XLogger.debug("Scheme ${uri.scheme}!");
                var canLaunch = await canLaunchUrl(uri);
                XLogger.debug("canLaunch: $uri");
                if (canLaunch) {
                  isMiniAppPay = false;
                  // Launch the App
                  XLogger.debug("launchUrl");
                  // 如果是打开支付宝app，修改fromAppUrlScheme为你的应用scheme。否则ios无法返回
                  var jumpUrl = uri.toString();
                  if (jumpUrl.startsWith('alipay://alipayclient')) {
                    jumpUrl = jumpUrl.replaceAll('alipays', 'alipay2021004123628706');
                  }
                  if (_isPayScheme(jumpUrl)) {
                    isLaunchAlipayApp = true;
                    isLaunchAlipayOpened = false;
                  }
                  await launchUrl(Uri.parse(jumpUrl));
                  return NavigationActionPolicy.CANCEL;
                } else {
                  XLogger.debug("Can't launch ${uri.toString()}!");
                }
              }
              if (uri.host.contains('wx.tenpay.com')) {
                // 判断请求头中是否包含Referer
                if (navigationAction.request.headers?.containsKey('Referer') == true) {
                  return NavigationActionPolicy.ALLOW;
                }
                // 获取redirect_url参数
                // final redirectUrl = uri.queryParameters['redirect_url'];
                // // 修改redirect_url参数
                // uri = uri.replace(queryParameters: {'redirect_url': 'xlwwh5.xlwwapp.top://wxpaycallback'});
                // XLogger.debug('redirectUrl: $uri');
                // 请求头中注入Referer
                await webViewController?.stopLoading();
                // await controller.loadUrl(urlRequest: URLRequest(url: uri, headers: {'Referer': 'https://xlwwh5.xlwwapp.top'}));
                await controller.loadUrl(
                    urlRequest: URLRequest(url: uri, headers: {'Referer': 'xlwwh5.xlwwapp.top://'}));
                return NavigationActionPolicy.CANCEL;
              }
              return NavigationActionPolicy.ALLOW;
            },
            // url拦截
            onLoadStart: (controller, url) async {
              // print('onLoadStart: $url');
              XLogger.debug('onLoadStart: $url');
              // 解析url的参数
              final uri = Uri.parse(url.toString());
              XLogger.debug('uri: ${uri.host}');
              if (uri.host.contains('xlwwapp.top') || uri.host.contains('192.168.31.120')) {
                isLaunchAlipayApp = false;
                if (isShowCountDown) {
                  // 停止倒计时
                  timerUtil.cancel();
                  setState(() {
                    isShowCountDown = false;
                  });
                }
                // 注入参数
                await _injectParams(uri);
                return;
              }
            },
            onLoadError: (controller, url, code, message) async {
              // print('onLoadError: $url -- code: $code -- message: $message');
              XLogger.debug('onLoadError: $url -- code: $code -- message: $message');
            },
          ),
          isShowCountDown
              ? Container(
                  alignment: Alignment.center,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      CircularPercentIndicator(
                        radius: 80.0,
                        lineWidth: 5.0,
                        percent: progress,
                        center: Text('${countDown}s', style: const TextStyle(fontSize: 36)),
                        progressColor: Colors.yellow,
                      ),
                      const SizedBox(height: 20),
                      Text('支付确认中...', style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryTextColor)),
                      const SizedBox(height: 60),
                      // 提示文字，多行，自动换行
                      const Padding(
                        padding: EdgeInsets.all(20),
                        child: Text(
                          '尊敬的用户，您好，如已支付但未充值到账，半小时后还不可使用，请在联系商铺或经销商客服。',
                          style: TextStyle(fontSize: 14, color: Colors.red),
                          textAlign: TextAlign.left,
                        ),
                      ),
                    ],
                  ))
              : Container(),
        ],
      ),
    );
  }
}
